import { Configure, Controller, GET, Params } from "../../lib/server";
import * as request from  'request'
import * as xml2js from 'xml2js'
import { resolve } from "url";

const WX_API = 'https://api.weixin.qq.com/sns/jscode2session'

type WxConfig = {
    id: string
    secret: string
    token: string
}


type AuthType = {
    session_key:string
    openid:string
}

@Controller('/wx')
class WeiXinController{

    private auth:AuthType

    @Configure('config','weixin_mini')
    private wxConfig:WxConfig
    @GET('/login')
    login(@Params('code') code:string){
        return new Promise((resolve,reject)=>{
            request.get({
                url:WX_API + `?appid=${this.wxConfig.id}&secret=${this.wxConfig.secret}&js_code=${code}&grant_type=authorization_code`,
            },(error,response,body)=>{
                if(error) return reject(error)
                try {
                    let res = JSON.parse(body)
                    if(res.errcode && res.errcode!=0) return reject(new Error(res.errmsg || '登录失败'))
                    if(res.errcode!=0) 
                    this.auth = res
                    resolve(this.auth.openid)
                } catch (error) {
                    reject(error)
                }
            })
        })
    }
}